<template>
	<el-drawer :title="titleMap[mode]" v-model="visible" :width="1100" destroy-on-close @closed="$emit('closed')">
		<div style="padding-left: 20px;padding-right: 20px">
			<el-alert
				v-if="checkStatus == 3"
				:title="reason"
				style="margin-bottom: 10px"
				type="error">
			</el-alert>
			<el-form :model="form" label-width="110px" :rules="rules" ref="ruleForm">
				<el-form-item>
					<template #label>
						<span style="color:#f56c6c;margin-right: 4px;">*</span>选择商品
					</template>
					<el-button type="primary" size="small" icon="el-icon-shopping-cart" @click="selectGoods">选择商品</el-button>
				</el-form-item>
				<el-form-item>
					<template #label>
						<span style="color:#f56c6c;margin-right: 4px;">*</span>选择规格
					</template>
					<el-table
						ref="multipleTable"
						:data="integralGoods"
						@selection-change="handleSelectionChange"
						style="width: 100%">
						<el-table-column
							type="selection"
							width="55">
						</el-table-column>
						<el-table-column v-for="(item,index) in tableHead" :label="item.label" :key="index">
							<template #default="scope">
								{{ scope.row.sku[item.property] }}
							</template>
						</el-table-column>
						<el-table-column
							label="图片">
							<template #default="scope">
								<img :src="scope.row.image" style="width: 40px;height: 40px"/>
							</template>
						</el-table-column>
						<el-table-column
							label="商品价格">
							<template #default="scope">
								{{ scope.row.goods_price }}
							</template>
						</el-table-column>
						<el-table-column
							label="兑换积分"
							width="120px">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.integral"></el-input>
							</template>
						</el-table-column>
						<el-table-column
							label="兑换金额"
							width="120px">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.price"></el-input>
							</template>
						</el-table-column>
						<el-table-column
							label="库存">
							<template #default="scope">
								{{ scope.row.goods_stock }}
							</template>
						</el-table-column>
						<el-table-column
							label="兑换库存">
							<template #default="scope">
								<el-input type="number" v-model="scope.row.stock"></el-input>
							</template>
						</el-table-column>
					</el-table>
				</el-form-item>
				<el-form-item label="商品标题" prop="name">
					<el-input v-model="form.name" placeholder="商品标题" style="width: 500px" clearable></el-input>
				</el-form-item>
				<el-form-item label="单次购买限制" prop="once_buy_limit">
					<el-input v-model="form.once_buy_limit" type="number" style="width: 500px" clearable></el-input>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<div class="dialog-footer">
				<el-button @click="visible = false">取 消</el-button>
				<el-button type="primary" @click="optSubmit('ruleForm')">立即提交</el-button>
			</div>
		</template>
		<el-dialog
			class="goods-select"
			title=""
			v-model="goodsDialogVisible"
			width="1000px">
			<goods-select @selected-goods="handleSelectedGoods" @close-dialog="goodsDialogVisible=false"></goods-select>
		</el-dialog>
	</el-drawer>
</template>

<script>
import goodsSelect from "@/components/goodsSingleSelect/index";

export default {
	emits: ['success', 'closed'],
	components: {
		goodsSelect
	},
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增积分商品',
				edit: '编辑积分商品',
				show: '查看'
			},
			integralGoods: [],
			form: {
				id: 0,
				name: '',
				image: '',
				goods_id: '',
				goods_rule: '',
				is_show: 2,
				once_buy_limit: 5,
				final: [],
				rule: []
			},
			rules: {
				name: [
					{ required: true, message: '请输入商品标题', trigger: 'blur' }
				],
				once_buy_limit: [
					{ required: true, message: '请输入单次购买数量', trigger: 'blur' }
				]
			},
			goodsDialogVisible: false,
			tableHead: [],
			visible: false,
			reason: '', // 拒绝原因
			checkStatus: 0
		}
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		// 新增或编辑
		optSubmit(formName) {
			this.$refs[formName].validate(async (valid) => {
				if (valid) {
					if (this.form.goods_rule == 2 && this.form.final.length == 0) {
						this.$message.error('请勾选积分商品')
						return false
					}

					if (this.form.goods_rule == 1 && this.form.goods_id == '') {
						this.$message.error('请勾选积分商品')
						return false
					}

					if (this.form.goods_rule == 1) {
						this.form.integral = this.integralGoods[0].integral
						this.form.price = this.integralGoods[0].price
						this.form.stock = this.integralGoods[0].stock
					} else {
						let sku2Info = new Map()
						this.integralGoods.forEach(item => {
							sku2Info.set(item.sku.join('※'), {
								integral: item.integral,
								price: item.price,
								stock: item.stock
							})
						})

						this.form.final.forEach((item, index) => {
							let key = item.sku.join('※')
							this.form.final[index].integral = sku2Info.get(key).integral
							this.form.final[index].price = sku2Info.get(key).price
							this.form.final[index].stock = sku2Info.get(key).stock
						})
					}

					this.loading = true
					let res;
					if (this.form.id) {
						res = await this.$API.integral.editGoods.post(this.form)
					} else {
						res = await this.$API.integral.addGoods.post(this.form)
					}
					this.loading = false
					if (res.code == 0) {
						this.$message.success(res.msg)
						this.$emit('success')
					} else {
						this.$message.error(res.msg)
					}
				}
			});
		},
		// 选择商品弹层
		selectGoods() {
			this.goodsDialogVisible = true
		},
		// 复选框选择商品
		handleSelectionChange(row) {
			if (row.length > 0) {
				this.form.goods_id = row[0].goods_id

				this.form.final = []
				if (this.form.goods_rule == 2) {
					row.forEach(item => {
						this.form.final.push({
							sku: item.sku,
							image: item.image,
							goods_id: item.goods_id,
							goods_price: item.goods_price,
							integral: parseInt(item.integral),
							price: item.price,
							goods_stock: item.stock,
							stock: item.stock
						});
					})
				}
			} else {
				this.form.image = ''
				this.form.goods_id = ''
				this.form.final = []
			}
		},
		// 点击确定选择的商品
		async handleSelectedGoods(row) {
			this.form.name = row[0].name
			this.form.goods_price = row[0].price
			// 单规格
			if (row[0].spec == 1) {
				this.integralGoods = [
					{
						image: row[0].pic,
						goods_id: row[0].id,
						goods_rule: '',
						goods_price: row[0].price,
						integral: parseInt(row[0].price),
						price: row[0].price,
						goods_stock: row[0].stock,
						stock: row[0].stock
					}
				];

				this.form.goods_rule = 1
				this.tableHead = []
			} else { // 多规格
				this.form.goods_rule = 2
				let res = await this.$API.goodsRule.getRuleByGoodsId.get({goods_id: row[0].id})
				// 原始商品的rule
				this.form.rule = JSON.parse(res.data.ruleData.rule)
				this.makeRule(JSON.parse(res.data.ruleData.rule), res.data.extend, 1)
			}

			this.goodsDialogVisible = false
		},
		// 生成规则
		makeRule(preItem, extend, type) {
			let titleMap = [];
			this.integralGoods = []
			preItem.forEach((item, index) => {
				let data = item.item.filter(function (s) {
					return s && s.trim();
				})
				if (item.title != '' && data.length > 0) {
					titleMap.push({label: item.title, property: index})
				}
			})

			if (type == 1) {
				extend.forEach(item => {
					this.integralGoods.push({
						id: item.id,
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.price,
						integral: parseInt(item.price),
						price: item.price,
						goods_stock: item.stock,
						stock: item.stock
					})
				})
			} else {
				extend.forEach(item => {
					this.integralGoods.push({
						id: item.id,
						sku: item.sku.split('※'),
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						integral: parseInt(item.integral),
						price: item.price,
						goods_stock: item.goods_stock,
						stock: item.stock
					})
				})
			}

			this.tableHead = titleMap
		},
		// 表单注入数据
		async setData(row) {

			let data = JSON.parse(JSON.stringify(row))
			this.title = '编辑积分商品'
			this.dialogVisible = true
			this.tableHead = []
			this.checkStatus = data.check_status
			this.reason = '拒绝原因：' + data.reason

			this.form = data
			let res = await this.$API.integral.getEditGoodsInfo.get({activity_id: data.id})
			if (res.code == 0) {
				this.form.once_buy_limit = data.once_buy_limit
				if (row.goods_rule == 2) { // 多规格
					this.form.rule = JSON.parse(data.integral_goods_rule)
					this.makeRule(JSON.parse(data.integral_goods_rule), res.data.jsonInfo, 2)
				} else { // 单规格
					this.form.rule = []

					this.integralGoods = []
					let item = res.data.jsonInfo[0]
					this.form.goods_price = res.data.jsonInfo[0].goods_price

					this.integralGoods.push({
						id: item.id,
						sku: '',
						image: item.image,
						goods_id: item.goods_id,
						goods_price: item.goods_price,
						integral: item.integral,
						price: item.price,
						goods_stock: item.goods_stock,
						stock: item.stock
					})
				}

				this.$nextTick(() => {
					this.integralGoods.forEach(item => {
						this.$refs.multipleTable.toggleRowSelection(item);
					})
				})
			}
		}
	}
}
</script>

<style scoped>

</style>
